#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2019/09/05
# @Author  : shengjin
# @FileName: 酷狗音乐下载.py

from tkinter import *
import requests
import json
import re

win = Tk()
win.title('酷狗音乐下载')
win.geometry("400x400")
label1 = Label(win,text="请输入歌曲名称:",font=("Consolas",15))
label1.pack()
entry1 = Entry(win,font=("Consolas",15))
entry1.pack()

def Request(url):#请求网址
    res = requests.get(url)
    return res

def Preser(url):#保存图片
    with open("音乐2.mp3","wb") as w:
        w.write(Request(url).content) 

def main():
    Musicname = entry1.get()
    url_head = 'http://songsearch.kugou.com/song_search_v2?callback=jQuery1124006980366032059648_1518578518932&keyword='+Musicname+'&page=1&pagesize=30&userid=-1&clientver=&platform=WebFilter&tag=em&filter=2&iscorrection=1&privilege_filter=0&_=1518578518934'
    #第一次请求音乐列表
    vsposer = Request(url_head)
    #正则匹配Hash值
    hash_base =re.findall(r'(?<=FileHash":").*?(?=")',re.findall(r'(?<=FileHash).*?(?=SQPayType)',vsposer.text)[0])[0] 
    #第一次请求音乐信息json
    resplor = Request('https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery191036326964422316266_1567674698850&hash='+hash_base+'&album_id=15270740&dfid=&mid=f7f2791bc23f547161c05b7eacc21657&platid=4&_=1567674698852')
    #正则匹配播放地址
    str = re.findall(r'(?<=play_url":).*?(?=,"authors)',resplor.text)[0]
    #保存音乐
    spyder = str.replace("\\","")
    Preser(spyder.replace('"',''))

if __name__ == "__main__":
    button = Button(win, text="下载",command=main,font=("Consolas",12))
    button.pack()
    win.mainloop()

